<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.security;
<%_ if (generateAuthenticationApi && (authenticationTypeOauth2 || authenticationTypeJwt)) { _%>

import <%= packageName %>.config.Constants;
<%_ } _%>

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
<%_ if (reactive) { _%>
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
<%_ } else { _%>
import org.springframework.security.core.context.SecurityContextHolder;
<%_ } _%>
import org.springframework.security.core.userdetails.UserDetails;
<%_ if (authenticationTypeJwt) { _%>
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.core.ClaimAccessor;
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
  <%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
  <%_ } else { _%>
import java.util.stream.Stream;
  <%_ } _%>
<%_ } else { _%>
import java.util.Arrays;
  <%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
  <%_ } else { _%>
import java.util.stream.Stream;
  <%_ } _%>
<%_ } _%>
<%_ if (authenticationTypeOauth2 || authenticationTypeJwt || !reactive) { _%>
import java.util.Optional;
<%_ } _%>
<%_ if (authenticationTypeOauth2 || authenticationTypeJwt) { _%>
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
<%_ } _%>
<%_ if (user?.primaryKey?.hasUUID) { _%>
import java.util.UUID;
<%_ } _%>

/**
 * Utility class for Spring Security.
 */
public final class SecurityUtils {
<%_ if (authenticationTypeOauth2) { _%>
    public static final String CLAIMS_NAMESPACE = "https://www.jhipster.tech/";
<%_ } else if (authenticationTypeJwt) { _%>

    public static final MacAlgorithm JWT_ALGORITHM = MacAlgorithm.HS512;

    public static final String AUTHORITIES_CLAIM = "auth";
  <%_ if (user) { _%>

    public static final String USER_ID_CLAIM = "userId";
  <%_ } _%>
<%_ } _%>

    private SecurityUtils() {}

    /**
     * Get the login of the current user.
     *
     * @return the login of the current user.
     */
    public static <% if (reactive) { %>Mono<% } else { %>Optional<% } %><String> getCurrentUserLogin() {
<%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .flatMap(authentication -> Mono.justOrEmpty(extractPrincipal(authentication)));
<%_ } else { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
<%_ } _%>
    }

    private static String extractPrincipal(Authentication authentication) {
        if (authentication == null) {
            return null;
        } else if (authentication.getPrincipal() instanceof UserDetails springSecurityUser) {
            return springSecurityUser.getUsername();
<%_ if (authenticationTypeJwt) { _%>
        } else if (authentication.getPrincipal() instanceof Jwt jwt) {
            return jwt.getSubject();
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
        } else if (authentication instanceof JwtAuthenticationToken) {
            return (String) ((JwtAuthenticationToken) authentication).getToken().getClaims().get("preferred_username");
        } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
            Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
            if (attributes.containsKey("preferred_username")) {
                return (String) attributes.get("preferred_username");
            }
<%_ } _%>
        } else if (authentication.getPrincipal() instanceof String s) {
            return s;
        }
        return null;
    }

<%_ if (authenticationTypeJwt) { _%>

    /**
     * Get the JWT of the current user.
     *
     * @return the JWT of the current user.
     */
    public static <% if (reactive) { %>Mono<% } else { %>Optional<% } %><String> getCurrentUserJWT() {
  <%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
  <%_ } else { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
  <%_ } _%>
            .filter(authentication -> authentication.getCredentials() instanceof String)
            .map(authentication -> (String) authentication.getCredentials());
    }
  <%_ if (user) { _%>

    /**
     * Get the Id of the current user.
     *
     * @return the Id of the current user.
     */
    public static <%- optionalOrMono %><<%= user.primaryKey.type %>> getCurrentUserId() {
    <%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
    <%_ } else { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
    <%_ } _%>
            .filter(authentication -> authentication.getPrincipal() instanceof ClaimAccessor)
            .map(authentication -> (ClaimAccessor) authentication.getPrincipal())
            .map(principal -> principal.getClaim(USER_ID_CLAIM));
    }
  <%_ } _%>
<%_ } _%>

    /**
     * Check if a user is authenticated.
     *
     * @return true if the user is authenticated, false otherwise.
     */
    public static <% if (reactive) { %>Mono<Boolean><% } else { %>boolean<% } %> isAuthenticated() {
<%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorities -> authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .noneMatch(AuthoritiesConstants.ANONYMOUS::equals)
            );
<%_ } else { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null &&
            getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
<%_ } _%>
    }

    /**
     * Checks if the current user has any of the authorities.
     *
     * @param authorities the authorities to check.
     * @return true if the current user has any of the authorities, false otherwise.
     */
    public static <% if (reactive) { %>Mono<Boolean><% } else { %>boolean<% } %> hasCurrentUserAnyOfAuthorities(String... authorities) {
<%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorityList ->
                authorityList
                    .stream()
                    .map(GrantedAuthority::getAuthority)
                    .anyMatch(authority -> Arrays.asList(authorities).contains(authority))
            );
<%_ } else { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (
            authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority))
        );
<%_ } _%>
    }

    /**
     * Checks if the current user has none of the authorities.
     *
     * @param authorities the authorities to check.
     * @return true if the current user has none of the authorities, false otherwise.
     */
    public static <% if (reactive) { %>Mono<Boolean><% } else { %>boolean<% } %> hasCurrentUserNoneOfAuthorities(String... authorities) {
<%_ if (reactive) { _%>
        return hasCurrentUserAnyOfAuthorities(authorities).map(result -> !result);
<%_ } else { _%>
        return !hasCurrentUserAnyOfAuthorities(authorities);
<%_ } _%>
    }

    /**
     * Checks if the current user has a specific authority.
     *
     * @param authority the authority to check.
     * @return true if the current user has the authority, false otherwise.
     */
    public static <% if (reactive) { %>Mono<Boolean><% } else { %>boolean<% } %> hasCurrentUserThisAuthority(String authority) {
        return hasCurrentUserAnyOfAuthorities(authority);
    }

<%_ if (!reactive) { _%>
    private static Stream<String> getAuthorities(Authentication authentication) {
  <%_ if (authenticationTypeOauth2) { _%>
        Collection<? extends GrantedAuthority> authorities = authentication instanceof JwtAuthenticationToken ?
            extractAuthorityFromClaims(((JwtAuthenticationToken) authentication).getToken().getClaims())
            : authentication.getAuthorities();
        return authorities.stream()
  <%_ } else { _%>
        return authentication.getAuthorities().stream()
  <%_ } _%>
            .map(GrantedAuthority::getAuthority);
    }

<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
    public static List<GrantedAuthority> extractAuthorityFromClaims(Map<String, Object> claims) {
        return mapRolesToGrantedAuthorities(getRolesFromClaims(claims));
    }

    @SuppressWarnings("unchecked")
    private static Collection<String> getRolesFromClaims(Map<String, Object> claims) {
        return (Collection<String>) claims.getOrDefault(
            "groups",
            claims.getOrDefault("roles", claims.getOrDefault(CLAIMS_NAMESPACE + "roles", new ArrayList<>()))
        );
    }

    private static List<GrantedAuthority> mapRolesToGrantedAuthorities(Collection<String> roles) {
        return roles.stream().filter(role -> role.startsWith("ROLE_")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }
<%_ } _%>
<%_ if (generateAuthenticationApi && ((authenticationTypeOauth2 && !syncUserWithIdp) || (authenticationTypeJwt && skipUserManagement))) { _%>

    public static Map<String, Object> extractDetailsFromTokenAttributes(Map<String, Object> attributes) {
        Map<String, Object> details = new HashMap<>();

        details.put("activated", Optional.ofNullable(attributes.get(StandardClaimNames.EMAIL_VERIFIED)).orElse(true));
        Optional.ofNullable(attributes.get("uid")).ifPresent(id -> details.put("id", id));
        Optional.ofNullable(attributes.get(StandardClaimNames.FAMILY_NAME)).ifPresent(lastName -> details.put("lastName", lastName));
        Optional.ofNullable(attributes.get(StandardClaimNames.PICTURE)).ifPresent(imageUrl -> details.put("imageUrl", imageUrl));

        Optional.ofNullable(attributes.get(StandardClaimNames.GIVEN_NAME)).ifPresentOrElse(
            firstName -> details.put("firstName", firstName),
            () -> Optional.ofNullable(attributes.get(StandardClaimNames.NAME)).ifPresent(firstName -> details.put("firstName", firstName))
        );

        if (attributes.get(StandardClaimNames.EMAIL) != null) {
            details.put("email", attributes.get(StandardClaimNames.EMAIL));
        } else {
            String sub = String.valueOf(attributes.get(StandardClaimNames.SUB));
            String preferredUsername = (String) attributes.get(StandardClaimNames.PREFERRED_USERNAME);
            if (sub.contains("|") && (preferredUsername != null && preferredUsername.contains("@"))) {
                // special handling for Auth0
                details.put("email", preferredUsername);
            } else {
                details.put("email", sub);
            }
        }

        if (attributes.get("langKey") != null) {
            details.put("langKey", attributes.get("langKey"));
        } else if (attributes.get(StandardClaimNames.LOCALE) != null) {
            // trim off country code if it exists
            String locale = (String) attributes.get(StandardClaimNames.LOCALE);
            if (locale.contains("_")) {
                locale = locale.substring(0, locale.indexOf('_'));
            } else if (locale.contains("-")) {
                locale = locale.substring(0, locale.indexOf('-'));
            }
            details.put("langKey", locale.toLowerCase());
        } else {
            // set langKey to default if not specified by IdP
            details.put("langKey", Constants.DEFAULT_LANGUAGE);
        }

        return details;
    }
<%_ } _%>
}
